package com.javenwong.android.engine.network;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

public class Highscores {
	
	public static String SERVICES_URL = "http://games.hrbyingli.com/MPGamesServices/top.do?m=";

	/**
	 * 获取排行（本方法包含联网和流操作，所以在调用时最好单开线程）
	 * @param gameId 游戏id, 必须
	 * @return List<Top>, 如返回null则读取失败
	 */
	public static List<Top> getTop(int gameId){
		return getTop(gameId, -1, null, -1);
	}
	
	/**
	 * 获取排行（本方法包含联网和流操作，所以在调用时最好单开线程）
	 * @param gameId 游戏id, 必须
	 * @param typeId 排行类型id, 默认为0, 可选-1
	 * @param sort	  排序方式 如(save2 desc), 默认为(save1 desc), 可选null
	 * @param max    读取最大记录数, 默认为10, 可选-1
	 * @return List<Top>, 如返回null则读取失败
	 */
	public static List<Top> getTop(int gameId, int typeId, String sort, int max){
		
		List<Top> data = new ArrayList<Top>();

		HttpURLConnection conn = null;
		InputStream in = null;
		
		try {
			StringBuffer sb = new StringBuffer();
			sb.append(SERVICES_URL).append("getTop");
			sb.append("&game_id="+gameId);
			if (typeId!=-1) sb.append("&type_id="+typeId);
			if (sort!=null) sb.append("&sort="+sort);
			if (max!=-1) sb.append("&max="+max);
			
			URL url = new URL(sb.toString());System.out.println("url:"+sb.toString());
			conn = (HttpURLConnection)url.openConnection();
			conn.setConnectTimeout(30000);
			conn.connect();
			in = conn.getInputStream();
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(in, "utf-8");
			int evtType = parser.getEventType();
			
			data = new ArrayList<Top>();
			
			while(evtType!=XmlPullParser.END_DOCUMENT){
				
				switch (evtType) {
				case XmlPullParser.START_TAG:
					String tag = parser.getName();
					
					if (tag.equals("top")){
						Top top = new Top((short)typeId, parser.getAttributeValue(0), 
								Integer.valueOf(parser.getAttributeValue(1)),
								Integer.valueOf(parser.getAttributeValue(2)),
								Integer.valueOf(parser.getAttributeValue(3)),
								Integer.valueOf(parser.getAttributeValue(4)),
								Integer.valueOf(parser.getAttributeValue(5)));
						data.add(top);
					}
					
					break;

				}
				
				evtType = parser.next();
			}
		} catch (Exception e) {
			data = null;
			e.printStackTrace();
		} finally{
			
			try {
				if (in!=null) in.close();
				if (conn!=null) conn.disconnect();
			} catch (IOException e) {
				
			}
		}
		
		return data;
	}
	
	/**
	 * 提交成绩（本方法包含联网和流操作，所以在调用时最好单开线程）
	 * @param gameId 游戏id, 必须
	 * @param name   玩家姓名, 必须
	 * @param saves  上传数据（最多5个数据）, 必须
	 * @return boolean true成功, false失败
	 */
	public static boolean submitScore(int gameId, String name, int[] saves){
		return submitScore(gameId, -1, name, saves);
	}
	
	/**
	 * 提交成绩（本方法包含联网和流操作，所以在调用时最好单开线程）
	 * @param gameId 游戏id, 必须
	 * @param typeId 排行类型id, 默认为0, 可选-1
	 * @param name   玩家姓名, 必须
	 * @param saves  上传数据（最多5个数据）, 必须
	 * @return boolean true成功, false失败
	 */
	public static boolean submitScore(int gameId, int typeId, String name, int[] saves){

		boolean ok = true;

		HttpURLConnection conn = null;
		InputStream in = null;
		
		try {
			StringBuffer sb = new StringBuffer();
			sb.append(SERVICES_URL).append("addTop");
			sb.append("&game_id="+gameId);
			if (typeId!=-1) sb.append("&type_id="+typeId);
//			sb.append("&name="+name);
			for(int saveid=0;saveid<saves.length;saveid++){
				sb.append("&save"+(saveid+1)+"="+saves[saveid]);
			}
//			
//			URL url = new URL(sb.toString());
//			conn = (HttpURLConnection)url.openConnection();
//			conn.setConnectTimeout(30000);
//			conn.connect();
//			in = conn.getInputStream();
//			InputStreamReader isr = new InputStreamReader(in);
//			BufferedReader reader = new BufferedReader(isr);
//			if (reader.readLine().trim().equals("yes")){
//				ok = true;
//			}else{
//				ok = false;
//			}
			
			HttpPost post = new HttpPost(sb.toString());
			
			List <NameValuePair> params = new ArrayList <NameValuePair>(); 
	        params.add(new BasicNameValuePair("name", name));
	        
			post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			HttpResponse httpResponse = new DefaultHttpClient().execute(post);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String strResult = EntityUtils.toString(httpResponse
						.getEntity());
				if (strResult.trim().equals("yes")){
					ok = true;
				}else{
					ok = false;
				}
			} else {
				ok = false;
			}

	        
		} catch (Exception e) {
			ok =false;
			e.printStackTrace();
		} finally{
			
			try {
				if (in!=null) in.close();
				if (conn!=null) conn.disconnect();
			} catch (IOException e) {
				
			}
		}
		
		return ok;
	}
}
